/**
 * 
 */
package com.net.service.chart;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.net.model.Pack;
import com.net.service.pack.PackageService;
import com.net.util.chart.PieTools;

/**
 *
 * @author fengcheng
 * @date 2018年6月25日 下午7:09:23
 */
public class PieServiceImpl implements PieService {

	/* (non-Javadoc)
	 * @see com.net.service.chart.PieService#createPieTools()
	 */
	@Override
	public JFreeChart createPieTools(String ip) {
		// TODO Auto-generated method stub
	    // 获取饼状图的数据集
	    DefaultPieDataset dataset = getDataSet(ip);
	    // 获取饼状图工具类创建的饼状图
	    JFreeChart chart = PieTools.createPie(dataset);
	    return chart;
	}
	/**
	 * 添加饼状图的数据
	 * 
	 * @return
	 */
	private static DefaultPieDataset getDataSet(String ip) {
		ApplicationContext ac = new ClassPathXmlApplicationContext(new String[] {
				"classpath:spring/ApplicationContext.xml", "classpath:spring/ApplicationContext-service.xml" });

		PackageService packageService = (PackageService) ac.getBean("packageService");
		List<Pack> packs=packageService.getPacketByIp(ip);
		int TCP=0,UDP=0,ARP=0,OTHER=0;
		for(Pack pack:packs){
			int len=pack.getPacket_len();
			String protocol=pack.getNet_protocol();
			if(protocol.equals("TCP")){
				TCP+=1;
			}else if(protocol.equals("UDP")){
				UDP+=1;
			}else if(protocol.equals("ARP")){
				ARP+=1;
			}else{
				OTHER+=1;
			}
		}
		
	    // 数据可以从数据库中得到
	    DefaultPieDataset dataset = new DefaultPieDataset();
	    // 添加数据
	    Map<String, Double> map = new HashMap<String, Double>();
	    map.put("TCP", (double) TCP);
	    map.put("UDP", (double) UDP);
	    map.put("ARP", (double) ARP);
	    map.put("其它", (double) OTHER);
	    Double sum = 0.0;
	    int count = map.size();
	    Set<String> keys = map.keySet();
	    for (String key : keys) {
	        sum += sum + map.get(key);

	    }
	    for (String key : keys) {

	        dataset.setValue(key, map.get(key));
	    }
	    // dataset.setValue("张三",30);
	    // dataset.setValue("李四",12);
	    // dataset.setValue("李四",12);
	    // dataset.setValue("王六",10);

	    return dataset;

	}

}
